local parser = require'lgx.parser'
local decl   = require'lgx.decl'
local alien  = require'lgx.gens.alien'
local lpeg   = require'lpeg'
local P, R, S, V, C = lpeg.P, lpeg.R, lpeg.S, lpeg.V, lpeg.C

args = {...}
args[1] = 'aliengl.xml'
if #args < 1 then
	print('usage: gen.lua <gccxmlfile>')
	os.exit(1)
end

fxml = io.open(args[1], 'r')
decls = parser.parse(fxml:read('*a'))
fxml:close()
codeset = decls:newcodeset('alien')
gl = codeset:query(function (d) 
    if d.tag ~= decl.FUNC then
        return false 
    elseif (string.find(d.name, 'gl')==1 or
           string.find(d.name, 'wgl')==1 ) and not string.find(d.name, 'glu') then
        d.stdcall = true
        return true
    else
        return false
    end
end)
glu = codeset:query(function (d) 
    if d.tag ~= decl.FUNC then
        return false 
    elseif string.find(d.name, 'glu')==1 then
        d.stdcall=true
        return true
    else
        return false
    end
end)
local header = 
[[
module('aliengl', package.seeall)
require'alien'
]]
print(header)
alien.LIBNAME = 'opengl32'
local glfuncs = {}
local glufuncs = {}
for i,v in ipairs(gl) do
    print(v:gencode())
    print(string.format('_G.%s = alien.%s.%s', v.name, alien.LIBNAME, v.name))
end
alien.LIBNAME = 'glu32'
for i,v in ipairs(glu) do
    print(v:gencode())
    print(string.format('_G.%s = alien.%s.%s', v.name, alien.LIBNAME, v.name))
end
glheader = io.open('GL.h', 'r')
gluheader = io.open('GLU.h', 'r')
patt = P'#define' * S' '^1 * C(P'GL_' * (1-S' \n')^1) * S' '^1 * C((1-S' \n')^1)

local flist = {glheader, gluheader}
for i, file in ipairs(flist) do
    for line in file:lines() do
        local name,value = lpeg.match(patt, line)
        if name and value then
            if string.find(value, 'GL') == 1 then
                value = '_G.'..value
            end
            print(string.format('_G.%s = %s', name, value))
        end
    end
    file:close()
end
